/**
 * Copyright 2009 by Christian Scheid. This file is part of the switch eclipse plugin and is licensed under the
 * GPL version 3. Please refer to the URL http://www.gnu.org/licenses/gpl-3.0.html for details.
 */
package org.digitalsoul.switchplugin.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;


public class ItemRing implements Iterable<ISwitchItem> {

    private int index = 0;
    private final List<ISwitchItem> items;
    
        public ItemRing() {
        items = new ArrayList<ISwitchItem>();
    }
    
    public void add(ISwitchItem item) {
        items.add(item);
    }
    
    public ISwitchItem next() {
        ISwitchItem item = items.get(index);
        index++;
        return item;
    }
    
    public void remove() {
       items.remove(index);
    }
    
    /**
     * this iterator does iterate once through the ring beginning from the last selected item
     */
    public Iterator<ISwitchItem> iterator() {
        return new ItemIterator(this);
    }
    
    public void spoolAfter(ISwitchItem currentItem) {
        index = items.indexOf(currentItem);
        if (index + 1 < items.size()) {
            index++;
        }
        else {
            index = 0;
        }
    }
    
    public void spoolTo(ISwitchItem currentItem) {
        index = items.indexOf(currentItem);
    }
    
    public void spoolBefore(ISwitchItem currentItem) {
        index = items.indexOf(currentItem);
        if (index > 0) {
            index--;
        }
        else {
            index = items.size()-1;
        }
    }
    
    public class ItemIterator implements Iterator<ISwitchItem> {

        private Iterator<ISwitchItem> iterator = null;
        
        public ItemIterator(ItemRing ring) {
            ArrayList<ISwitchItem> list = new ArrayList<ISwitchItem>();
            for (int i = ring.index; i < ring.items.size(); i++) {
                list.add(ring.items.get(i));
            }
            for (int i = 0; i < ring.index; i++) {
                list.add(ring.items.get(i));
            }
            iterator = list.iterator();
        }
        
        public boolean hasNext() {
            return iterator.hasNext();
        }

        public ISwitchItem next() {
            return iterator.next();
        }

        public void remove() {
            throw new RuntimeException("not implemented aaargh");
        }
    }

    public Collection<ISwitchItem> items() {
        return items;
    }
    
    public void clear() {
        items.clear();
        index = 0;
    }
}
